import React from 'react';
import './refundOrderList.less';
import { Breadcrumb, Row, Col, Input, DatePicker, Select, Button, Table, Pagination, Modal, Upload, Icon, message } from 'antd';
import { Link } from 'react-router';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';

const { RangePicker } = DatePicker;
const Option = Select.Option;
const config = new Config();
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');

class refundOrderList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: JSON.parse(sessionStorage.getItem('UserInfo')).userid, // 操作人用户ID
      data: [], // 订单数据
      text: '', // 搜索值
      date: [], // 时间
      serviceType: undefined, // 服务类型
      isRefund: undefined, // 处理结果
      page: 1, // 当前页
      pageSize: 10, // 每页显示的条数
      total: 0, // 总数
      refundOrder: {}, // 退款订单
      refundVisible: false, // 退款显示
      confirmRefundVisible: false, // 确认退款显示
      voucher: '', // 凭证

      onLineVisible: false, // 线上退款模态框
    }
    this.InputText = this.InputText.bind(this);
    this.changeDate = this.changeDate.bind(this);
    this.selectServiceType = this.selectServiceType.bind(this);
    this.selectHandleResult = this.selectHandleResult.bind(this);
    this.onChangePage = this.onChangePage.bind(this);
    this.hiddenRefund = this.hiddenRefund.bind(this);
    this.hiddenconfirmRefund = this.hiddenconfirmRefund.bind(this);
    this.updateImg = this.updateImg.bind(this);
    this.confirmRefund = this.confirmRefund.bind(this);
    this.onLineRefund = this.onLineRefund.bind(this);
  }

  componentDidMount() {
    this.getData();
  }

  //获取订单数据
  getData() {
    const date = this.state.date;
    const beginDate = date[0] ? date[0].format('YYYY-MM-DD') : '';
    const endDate = date[1] ? date[1].format('YYYY-MM-DD') : '';
    $.ajax({
      url: `${config.JuseOrder}/refundOrder/list`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        text: this.state.text,
        beginDate,
        endDate,
        serviceType: this.state.serviceType,
        isRefund: this.state.isRefund,
        page: this.state.page,
        pageSize: this.state.pageSize
      },
      success: (res) => {
        console.log('退款列表', res);
        if (res.code === 200) {
          res.data.rows.forEach((item, index) => {
            item.key = index + 1 + (this.state.page - 1) * this.state.pageSize;
          });
          this.setState({
            data: res.data.rows,
            total: res.data.count
          });
        }
      }
    });
  }

  // 表头
  getColumns() {
    return [{
      title: '序号',
      width: '4%',
      dataIndex: 'key'
    }, {
      title: '订单编号',
      width: '12%',
      render(record) {
        return <Link to={'/refundOrderDetail/' + record.orderId}>{record.orderId}</Link>
      }
    }, {
      title: '退款编号',
      width: '12%',
      dataIndex: 'refundId'
    }, {
      title: '交易金额',
      width: '9%',
      render(record) {
        return `${record.money}(${record.paymentMethod})`
      }
    }, {
      title: '退款金额',
      width: '9%',
      dataIndex: 'refundMoney'
    }, {
      title: '服务类型',
      width: '7%',
      dataIndex: 'serviceType'
    }, {
      title: '申请时间',
      width: '10%',
      render(record) {
        return moment(Number(record.refundDate)).format('YYYY-MM-DD HH:mm')
      }
    }, {
      title: '处理时间',
      width: '10%',
      render(record) {
        return moment(Number(record.handleDate)).format('YYYY-MM-DD HH:mm')
      }
    }, {
      title: '退款状态',
      width: '9%',
      render(record) {
        let text;
        switch (record.isRefund) {
          case 0:
            text = '待退款';
            break;
          case 1:
            text = <span>退款成功</span>;
            break;
        }
        return text;
      }
    }, {
      title: '已退款凭证图片',
      width: '9%',
      render(record) {
        if (record.voucher) {
          return <img src={record.voucher.split(',')[0]} style={{ width: 50, height: 50 }} />
        }
      }
    }, {
      title: '操作',
      width: '9%',
      render: (record) => {
        if (!record.isRefund) {
          // if (record.paymentMethod === '货到付款') {
          return <a href='javascript:void(0)' onClick={this.showConfirmRefund.bind(this, record)}>退款</a>
          // } else {
          //   return <a href='javascript:void(0)' onClick={this.showOnLineRefund.bind(this, record)}>退款</a>
          // }
        }
      }
    }];
  }

  // 输入搜索值
  InputText(e) {
    this.setState({
      text: e.target.value
    });
  }

  // 选择日期
  changeDate(date) {
    this.setState({
      date
    });
  }

  // 选择服务类型
  selectServiceType(value) {
    this.setState({
      serviceType: value
    });
  }

  // 选择处理结果
  selectHandleResult(value) {
    this.setState({
      isRefund: value
    });
  }

  // 搜索/清空
  filterOrders(key) {
    if (key) {
      // 搜索
      this.setState({
        page: 1
      }, () => {
        this.getData();
      });
    } else {
      // 清空
      this.setState({
        text: '',
        date: [],
        serviceType: undefined,
        isRefund: undefined
      }, () => {
        this.getData();
      });
    }
  }

  // 切换分页
  onChangePage(page) {
    this.setState({
      page
    }, () => {
      this.getData();
    });
  }

  // 显示线上退款模态框
  showOnLineRefund(order) {
    this.setState({
      onLineVisible: true,
      refundOrder: order
    });
  }

  // 隐藏退款
  hiddenRefund() {
    this.setState({
      onLineVisible: false,
      refundOrder: {}
    });
  }

  // 显示确认退款
  showConfirmRefund(order) {
    this.setState({
      confirmRefundVisible: true,
      refundOrder: order
    });
  }

  // 隐藏确认退款
  hiddenconfirmRefund() {
    this.setState({
      confirmRefundVisible: false,
      refundOrder: {}
    });
  }

  // 限制用户必须上传图片格式的文件、图片大小和数量
  beforeUpload(file) {
    console.log(file.type)
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
      message.error('您只能上传图片！');
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('您上传的图片大小必须小于10MB！');
    }
    return isJPG && isLt10M;
  }

  // 上传图片
  updateImg(file) {
    console.log(file);
    const list = [];
    file.fileList.forEach(item => {
      if (item.response && item.response.code === 200) {
        list.push(config.Filepath + item.response.name);
      }
    });
    this.setState({
      voucher: list.join(',')
    });
  }

  // 确认退款
  confirmRefund() {
    const voucher = this.state.voucher;
    console.log(voucher, this.state.refundOrder, this.state.userId);
    if (!voucher) {
      return message.error('未上传图片或上传失败，请重新上传');
    }
    $.ajax({
      url: `${config.JuseOrder}/refundOrder/confirmRefund`,
      type: 'post',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        refundId: this.state.refundOrder.refundId,
        voucher,
        voucherPersonId: this.state.userId
      },
      success: (data) => {
        console.log('确认退款', data);
        if (data.code === 200) {
          message.success('退款成功');
          this.setState({
            refundOrder: {},
            voucher: '',
            confirmRefundVisible: false
          }, () => {
            this.getData();
          });
        } else {
          message.error(data.mes);
        }
      }
    });
  }

  // 线上退款
  onLineRefund() {
    console.log('待做');
    message.warning('待做');
  }

  render() {
    const columns = this.getColumns();
    return (
      <div className='contentBox clearfix'>
        <div className='breadcrumb'>
          <Breadcrumb separator=">">
            <Breadcrumb.Item>订单管理</Breadcrumb.Item>
            <Breadcrumb.Item>退款列表</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className="member-content-Search">
          <div className='orderfilter'>
            <div className='addetd addetd-z' style={{ zIndex: 1 }}>
              <Input className='lhpx' addonBefore='请输入订单编号、退货编号' placeholder="请输入" value={this.state.text} onChange={this.InputText} />
            </div>
            <div className='addetd addetd1'>
              <Input className='addetd-a-r' addonBefore="申请时间" placeholder="请输入" value={this.state.Inkey} onChange={(e) => this.changeInkey(e)} />
              <RangePicker
                format='YYYY-MM-DD'
                placeholder={['请选择日期', '请选择日期']}
                onChange={this.changeDate}
                value={this.state.date}
              />
            </div>
            <div className='addetd addetd1 addetd-ght addetd-ght-1'>
              <InputGroup compact>
                <Input addonBefore="服务类型" />
                <Select value={this.state.serviceType} onChange={this.selectServiceType.bind(this)} allowClear>
                  <Option value='退款'>退款</Option>
                  <Option value='代客退款'>代客退款</Option>
                </Select>
              </InputGroup>
            </div>
            <div className='addetd addetd1 addetd-ght addetd-ght-1'>
              <InputGroup compact>
                <Input addonBefore="处理结果" />
                <Select placeholder='请选择' value={this.state.isRefund} onChange={this.selectHandleResult.bind(this)} allowClear>
                  <Option value='0'>待退款</Option>
                  <Option value='1'>退款成功</Option>
                </Select>
              </InputGroup>
            </div>

            <Button className='ant-btn-primary' icon='search' onClick={this.filterOrders.bind(this, 1)}>搜索</Button>
            <Button className='ant-btn-primary' icon='sync' onClick={this.filterOrders.bind(this, 0)}>重置</Button>
          </div>
        </div>
        <div className='allgoods-table clearfix'>
          <Table columns={columns} dataSource={this.state.data} pagination={false} bordered />
        </div>
        <div className='goods-label-let'>
          <div className="floor-ppagi">
            {
              this.state.total == 0 ?
                <p className="floor-ppagip">
                  共{this.state.total}条记录
              </p> :
                <p className="floor-ppagip">
                  当前显示
                  {this.state.pageSize * (this.state.page - 1) + 1}—
                  {this.state.pageSize * this.state.page < this.state.total ? this.state.pageSize * this.state.page : this.state.total}条记录，
                  共{this.state.total}条记录
              </p>
            }
            <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pageSize} onChange={this.onChangePage.bind(this)} />
          </div>
        </div>
        <Modal
          visible={this.state.onLineVisible}
          onOk={this.onLineRefund}
          onCancel={this.hiddenRefund}
          closable={false}
        >
          <p className='bianfc'>退款金额：{this.state.refundOrder.refundMoney}(元)</p>
          <p className='bianfc1'>一经退款，款项将原路返回至客户账号，确认立即操作？</p>
        </Modal>
        <Modal
          visible={this.state.confirmRefundVisible}
          onOk={this.confirmRefund}
          onCancel={this.hiddenconfirmRefund}
          closable={false}
          className={'gergb'}
        >
          <p>
            <label>退款金额：</label>
            <span>{this.state.refundOrder.refundMoney}(元)</span>
          </p>
          <p>
            <label>退款账户：</label>
            <span>{this.state.refundOrder.refundAccountNumber}</span>
          </p>
          <p>
            <label>账户名：</label>
            <span>{this.state.refundOrder.refundUserName}</span>
          </p>
          <div>
            <label>打款凭证：</label>
            <Upload
              name='Filedata'
              action={config.UploadFile + '/uploadrecipeimg'}
              listType='picture'
              beforeUpload={this.beforeUpload}
              onChange={this.updateImg}
            >
              <Button>
                <Icon type="upload" /> 上传图片
              </Button>
            </Upload>
          </div>
          <p>
            <label></label>
            <span>是否已经确认把退款打到对方账号？</span>
          </p>
        </Modal>
      </div>
    )
  }
}

export default refundOrderList;
